'''
Created on 2021年1月15日

@author: Administrator
'''
import datetime,time

from dateutil.relativedelta import relativedelta
from flask import json
from peewee import JOIN, fn

from common.public import *
from orm.model import db,Matter, AgentKeeping, Document, Dept , TransForm, WorkOrderDetails, Customer, ServiceDetail, AgentKeepingDetails, User, \
    TransFormDetail
import pandas as pd
from view.baseview import BaseView


class KeepAccountView(BaseView):

    def __init__(self):
        pass

    # 通过公司名称远程搜索公司id
    def queryKeepAccountCustomer(self, querycustomer):
#         print(querycustomer)
        result =[]
        where_condition =True
        if querycustomer:
            likestr = querycustomer+"%"
            where_condition=(Customer.compname ** likestr)
        rows = Customer.select().where(where_condition).order_by(Customer.updatetime.desc())
        for row in rows:
            data = {
                "value":row.id,
                "label":row.compname,
             }
            result.append(data)
        return super().resultSet(200, "", result)

    # 查询代理记账信息
    def queryKeepAccount(self, params):
        """params：条件参数"""
        result = []
        where_condition = True

        # 取得所有用户,放进hasMap
        usermap = {}
        allusers = User.select()
        for user in allusers:
            usermap[user.id] = user.username

        where_details_condition = True
        whereDetail_condition = True
        if params["keyword"]:
            likestr = "%" + params["keyword"] + "%"
            where_condition = (Customer.compname ** likestr)
            where_condition = where_condition | (Customer.contacter ** likestr)
            where_condition = where_condition | (Customer.address ** likestr)
            where_condition = where_condition | (Customer.phone ** likestr)
            where_condition = where_condition | (Customer.memo ** likestr)
            where_condition = where_condition | (Document.document_number ** likestr)
            where_condition = where_condition | (AgentKeeping.contract_number ** likestr)
            where_condition = where_condition | (Customer.taxtype ** likestr)
        # 取得部门管辖区域
        if params["userid"]:
            user = User.get(User.id == params["userid"])
            # 取得部门列表ID
            deptids = Dept.select(Dept.id).where(Dept.up_id == user.dept_id)
            if deptids:
                # 如果取到部门列表，说明是总经办部门人员
                pass
            else:
                # 如果取不到部门列表，说明是总经办部门以外人员
                leader = User.select().where(User.id == params["userid"]).first()
                ids = []
                if leader.isleader == COMMON_TRUE:
                    # 如果是主管
                    rows = User.select(User.id).where(User.leader_id == params["userid"])
                    for row in rows:
                        ids.append(row.id)
                    ids.append(params["userid"])
                else:
                    ids.append(params["userid"])
                     # set方法保证负责人不重复
                    personnelchargerIds = set([])
                    # 取得相关人员的明细ID
                    agentkeepdetailrows = AgentKeepingDetails.select(AgentKeepingDetails.keepaccount_id).where(AgentKeepingDetails.charger_id.in_(ids))
                    for agentkeepdetailrow in agentkeepdetailrows:
                        personnelchargerIds.add(agentkeepdetailrow.keepaccount_id)        
                    where_condition = where_condition & (AgentKeeping.leader_id.in_(ids) | AgentKeeping.id.in_(personnelchargerIds))

        if params["renew"]:
            where_condition = where_condition & (
                AgentKeeping.renew == params["renew"])

        if params["endTime"]:
            where_condition = where_condition & ((AgentKeeping.enddate >= params["endTime"][0] + " 00:00:00")
                                                 & (AgentKeeping.enddate <= params["endTime"][1] + " 23:59:59"))
        if params["createTime"]:
            where_condition = where_condition & ((AgentKeeping.create_time >= params["createTime"][0] + " 00:00:00")
                                                 & (AgentKeeping.create_time <= params["createTime"][1] + " 23:59:59"))
        # if params["updateTime"]:
        #     where_condition = where_condition & ((AgentKeeping.update_time >= params["updateTime"][0] + " 00:00:00")
        #                                          & (AgentKeeping.update_time <= params["updateTime"][1] + " 23:59:59"))

        where_condition = where_condition & (
            AgentKeeping.name == '代理记账')
        if params["taxGroup"]:
            where_condition = where_condition & (Document.tax_group == (params["taxGroup"]))
        if params["taxtype"]:
            if params["taxtype"] == "空白":
                params["taxtype"] = None
            where_condition = where_condition & (Customer.taxtype == (params["taxtype"]))
        if params["TCP"]:
            if params["TCP"] == "空白":
                params["TCP"] = None
            where_condition = where_condition & (AgentKeeping.TCP == (params["TCP"]))
        if params["sbgjj"]:
            if params["sbgjj"] == "空白":
                params["sbgjj"] = None
            where_condition = where_condition & (AgentKeeping.sbgjj == (params["sbgjj"]))

        if params["month"]:
            where_details_condition = where_details_condition & (AgentKeepingDetails.month == params["month"])
        if params["status"]:
            where_details_condition = where_details_condition & (AgentKeepingDetails.status == params["status"])

        if params["personnel"]:
            where_condition = where_condition & (AgentKeepingDetails.charger.in_(params["personnel"])) | (AgentKeeping.leader_id.in_(params["personnel"]))



        if params["distinct"] == '不显示':
            # 按最新账本，去除重复公司名称的账本
            rows = AgentKeeping.select(AgentKeeping.id,fn.Max(AgentKeeping.enddate))\
                .join(Customer, JOIN.LEFT_OUTER, on = (AgentKeeping.customer_id == Customer.id))\
                .join(ServiceDetail, JOIN.LEFT_OUTER, on=(AgentKeeping.servicedetail_id == ServiceDetail.id))\
                .join(Document, JOIN.LEFT_OUTER, on = (AgentKeeping.document_id == Document.id))\
                .join(AgentKeepingDetails, JOIN.LEFT_OUTER, on=(AgentKeeping.id == AgentKeepingDetails.keepaccount_id))\
                .where(where_condition & where_details_condition) \
                .group_by(AgentKeeping.customer_id) \
                .order_by((Document.document_number *1))
        else:
            # 先找出所有符合条件的账本id
            rows = AgentKeeping.select(fn.Distinct(AgentKeeping.id),AgentKeeping.enddate)\
                .join(Customer, JOIN.LEFT_OUTER, on = (AgentKeeping.customer_id == Customer.id))\
                .join(ServiceDetail, JOIN.LEFT_OUTER, on=(AgentKeeping.servicedetail_id == ServiceDetail.id))\
                .join(Document, JOIN.LEFT_OUTER, on = (AgentKeeping.document_id == Document.id))\
                .join(AgentKeepingDetails, JOIN.LEFT_OUTER, on=(AgentKeeping.id == AgentKeepingDetails.keepaccount_id))\
                .where(where_condition & where_details_condition) \
                .order_by((Document.document_number *1))
        # 数量
        total = len(rows)
        # 分页
        rows = rows.paginate(int(params["pageNo"]), int(params["pagesize"]))

        for rec in rows:
            row = AgentKeeping.get(AgentKeeping.id == rec.id)
            if row.create_time != None:
                row.create_time = time.strftime(
                    "%Y-%m-%d", time.strptime(str(row.create_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime(
                    "%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
            if row.document_id is None:
                documentNumber = ""
                taxGroup = 0
                taxGroupName = ""
            else:
                documentNumber = row.document.document_number
                deptrow = Dept.select().where(Dept.id == row.document.tax_group).first()
                taxGroup = 0
                taxGroupName = ""
                if deptrow != None:
                    taxGroup = deptrow.id
                    taxGroupName = deptrow.name
            recs = []
            # if not params["month"]:
            #     where_details_condition = True
            keepaccountrows = AgentKeepingDetails.select()\
                .join(Matter, JOIN.LEFT_OUTER, on = (Matter.name == AgentKeepingDetails.matter))\
                .where((AgentKeepingDetails.keepaccount_id == row.id) & where_details_condition)\
                .order_by(AgentKeepingDetails.month.asc(),Matter.sort)
            for keepaccountrow in keepaccountrows:
                chargername = ""
                if keepaccountrow.charger_id != 0:
                    chargername =usermap[keepaccountrow.charger_id]
#                 print(keepaccountrow.matter,keepaccountrow.month,chargername)
                if keepaccountrow.create_time != None:
                    keepaccountrow.create_time = time.strftime(
                        "%Y-%m-%d", time.strptime(str(keepaccountrow.create_time), "%Y-%m-%d %H:%M:%S"))
                if keepaccountrow.update_time != None:
                    keepaccountrow.update_time = time.strftime(
                    "%Y-%m-%d", time.strptime(str(keepaccountrow.update_time), "%Y-%m-%d %H:%M:%S"))
                # 如果charger_id为空则不显示名字，否则显示之前map方法的value（名字）
                if keepaccountrow.charger_id != 0 & keepaccountrow.charger_id != None:
                    if (keepaccountrow.month[5:8] in ["01", "04", "07", "10"]) & (keepaccountrow.matter in COPY_TAX_NATIONAL_TAX_SMALL_SCALE_QUARTER):
                        chargername = usermap[keepaccountrow.charger_id]
                    elif (keepaccountrow.matter in CONTENT_OF_KEEPINGING_AGENT_EVERY_MONTH):
                        chargername = usermap[keepaccountrow.charger_id]
                    else:
                        chargername = ""
                # # 抄税 小规模季度, 国税 小规模季度中，只有1,4,7,10月显示更新时间
                # updateTime = keepaccountrow.update_time if (keepaccountrow.month[5:8] in ["01", "04", "07", "10"]) & (keepaccountrow.matter in COPY_TAX_NATIONAL_TAX_SMALL_SCALE_QUARTER) else ""
                # # 其他4个事项都显示时间，不是这4个事项按上面的更新时间显示
                # updateTime = keepaccountrow.update_time if (keepaccountrow.matter in CONTENT_OF_KEEPINGING_AGENT_EVERY_MONTH) else updateTime
                # # 抄税 小规模季度, 国税 小规模季度中，只有1,4,7,10月显示状态
                # status = keepaccountrow.status if (keepaccountrow.month[5:8] in ["01", "04", "07", "10"]) & (keepaccountrow.matter in COPY_TAX_NATIONAL_TAX_SMALL_SCALE_QUARTER) else ""
                # # 其他4个事项都显示状态，不是这4个事项按上面的状态显示
                # status = keepaccountrow.status if (keepaccountrow.matter in CONTENT_OF_KEEPINGING_AGENT_EVERY_MONTH) else status
                # 如果没有税控盘并且办理事项是抄税 小规模季度,清卡 每月，也不显示负责人，更新时间，状态
                # if (row.TCP == "无") & (keepaccountrow.matter in COPY_TAX_NATIONAL_TAX_CLEARN_TAX):
                #     chargername =""
                #     updateTime =""
                #     status=""
                recs.append({"id":keepaccountrow.id,
                "keepaccountid":keepaccountrow.keepaccount_id,
                "chargerId":keepaccountrow.charger_id,
                "charger":chargername,
                "matter":keepaccountrow.matter,
                "status":keepaccountrow.status,
                "remake":keepaccountrow.remake,
                "evidence":json.loads(keepaccountrow.evidence),
                "month":keepaccountrow.month,
                # "updateTime":updateTime,
                "createTime":keepaccountrow.create_time
                })
            # newmatter = ""
            # newstatus = ""
            # 取得最新事项，并更新到主表
            # updatekeepaccountfirstrow = AgentKeepingDetails.select().where(AgentKeepingDetails.keepaccount_id == row.id).order_by(AgentKeepingDetails.update_time.desc()).first()
            # if updatekeepaccountfirstrow != None:
            #     newmatter = updatekeepaccountfirstrow.matter
            #     newstatus = updatekeepaccountfirstrow.status
            # print(row.customer.id)
            data = {
                "id": row.id,
                "servicedetailId": row.servicedetail_id,
                "taxtype": row.customer.taxtype,
                "leader":row.leader.username,
                "leaderId":row.leader.id,
                "transformId": row.transform_id,
                "unit":row.unit,
                "amount":row.amount,
                "retry":"否",
                "status":row.status,
                "renew": row.renew,
                "customer_id":row.customer_id,
                "name": row.name,
                "compname": row.customer.compname,
                "contacter": row.customer.contacter,
                "phone": row.customer.phone,
                "remake": row.remake,
                "contractNumber":row.contract_number,
                "documentNumber":documentNumber,
                "taxGroup":taxGroup,
                "taxGroupName":taxGroupName,
                "TCP":row.TCP,
                "sbgjj":row.sbgjj,
                "createTime": row.create_time,
                "updateTime": row.update_time,
                "enddate":  time.strftime("%Y-%m-%d", time.strptime(str(row.enddate), "%Y-%m-%d %H:%M:%S")),
                "recs":recs
                }
            result.append(data)
        return super().resultSet(200, "", result, total)
    
    @db.atomic()                   
    def distributeKeepAccount(self, params):
        """
        分配
        """
#         print(params)
        # 更新负责人期限
        keepaccount = AgentKeeping.get(AgentKeeping.id == params["id"])
        keepaccount.contract_number = params["contractNumber"]
        keepaccount.TCP = params["TCP"]
        keepaccount.leader_id = params["leaderId"]
        keepaccount.remake = params["remake"]
        keepaccount.renew = params["renew"]
        keepaccount.enddate = params["enddate"]
        keepaccount.amount = params["amount"]
        # 如果档案不存在，则创建新档案，如果存在则取得档案
        document, created = Document.get_or_create(customer_id = keepaccount.customer_id , defaults = {'customer_id': keepaccount.customer_id})
    
        document.document_number = params["documentNumber"]
        document.tax_group = params["taxGroup"]
        keepaccount.document_id = document.id
        keepaccount.save()
        document.save()
        
        if params["retry"] == "是":
            # 先删除旧的账本
            AgentKeepingDetails.delete().where(AgentKeepingDetails.keepaccount_id == params["id"]).execute()
            # 重新生成账本
            enddate = params["enddate"][0:10]
            # 截止日期转换为日期型
            new_time = datetime.datetime.strptime(enddate, '%Y-%m-%d')
            months = int(params["amount"])
            # 因为开闭取不到最后截止日期,所以这边截止日期加1个月
            new_time = new_time + relativedelta(months = 1)
            # 倒推开始日期
            month_ago = new_time - relativedelta(months = months)
            # 截止日期开始日期转换为str类型
            new_timestr = new_time.strftime('%Y%m%d')
            month_agostr = month_ago.strftime('%Y%m%d')
            # 使用pandas库列出开始日期到截止日期中的月份
            year_month_list = pd.date_range(start = month_agostr, end = new_timestr, freq = 'M').tolist()   
            data_year_months = year_month_list 
            # 未完成
            status = KEEPINGING_AGENT_STATUS_FAIL
            result = []
            for month in data_year_months:
                # 现在日期
                now_timestr = datetime.datetime.now()           
                # to_pydatetime()方法，把list中的月份和现在日期比较
                if month.to_pydatetime() >= now_timestr:
                    # 本月之后的默认未完成
                    status = KEEPINGING_AGENT_STATUS_FAIL
                elif month.to_pydatetime() < now_timestr:
                    # 本月之前的默认已完成
                    status = KEEPINGING_AGENT_STATUS_SUCCESS  
                # 只取年月
                month = month.strftime("%Y-%m")
                for item in params["members"]:
                    data = {
                        "keepaccount_id": params["id"],
                        "charger_id": item["chargerId"],
                        "matter": item["name"],
                        "status":status,
                        "month":month,
                        "remake": '无',
                        "evidence": '[]',
                        "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        "create_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                        }
                    result.append(data)
            AgentKeepingDetails.insert_many(result).execute()        
        
        # 修改月份负责人
        for member in params["members"]:
            AgentKeepingDetails.update(charger_id=member["chargerId"])\
            .where((AgentKeepingDetails.keepaccount_id==keepaccount.id) & \
                   (AgentKeepingDetails.matter==member["name"])).execute();
        
        


        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    
    
    @db.atomic()                   
    def addKeepAccountItem(self, params):
        """
      新增
        """
        # 用正则表达式把证据转换为json格式
        params["evidence"] = str(params["evidence"]).replace("'", "\"").replace(r"\n", "")
        AgentKeepingDetails.create(
            keepaccount_id = params['keepaccountId'],
            charger_id = params["chargerId"],
            matter = params["matter"],
            status = params["status"],
            month = params["enddate"],
            remake = params["remake"],
            evidence = params["evidence"],
            enddate = params['enddate'],
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")
    
    @db.atomic()                   
    def editKeepAccountItem(self, params):
        """
      修改
        """
        # 用正则表达式把证据转换为json格式
        params["evidence"] = str(params["evidence"]).replace("'", "\"").replace(r"\n", "")
        keepaccountdetail = AgentKeepingDetails.get(AgentKeepingDetails.id == params["id"])
        keepaccountdetail.status = params["status"]
        keepaccountdetail.month = params["enddate"]
        keepaccountdetail.charger_id = params["chargerId"]
        keepaccountdetail.matter = params["matter"]
        keepaccountdetail.remake = params["remake"]
        keepaccountdetail.evidence = params["evidence"]
        keepaccountdetail.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        keepaccountdetail.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("更新失败")
    
    @db.atomic()                   
    def removeKeepAccountItem(self, params):
        """
                              删除事项
        """
        keepaccountdetail = AgentKeepingDetails.get(AgentKeepingDetails.id == params["id"])
        keepaccountdetail.delete_instance()
        return super().resultSet(200, "删除成功", [])
        raise Exception("更新失败")

    @db.atomic()                   
    def removeKeepAccount(self, params):
        """
                              删除
        """
        agentkeeping = AgentKeeping.get(AgentKeeping.id == params["id"])
        # 删除详情
        AgentKeepingDetails.delete().where(AgentKeepingDetails.keepaccount_id == params["id"]).execute()
        # 删除实例
        agentkeeping.delete_instance()
        return super().resultSet(200, "删除成功", [])
        raise Exception("更新失败")

    @db.atomic()                   
    def removeMulKeepAccount(self, params):
        """
                              删除
        """
        AgentKeepingDetails.delete().where(AgentKeepingDetails.keepaccount_id.in_(params["ids"])).execute()
        AgentKeeping.delete().where(AgentKeeping.id.in_(params["ids"])).execute()
        return super().resultSet(200, "删除成功", [])
        raise Exception("更新失败")

    @db.atomic()                   
    def addAgentKeeping(self, params):
        """
        添加代理记账
        """
        # 如果档案不存在，则创建新档案，如果存在则取得档案
        document, created = Document.get_or_create(customer_id = params["customerId"] , defaults = {'customer_id': params["customerId"]})
        document.document_number = params["documentNumber"]
        document.tax_group = params["taxGroup"]
        document.save()

        agentkeeping = AgentKeeping.create(
            transform_id = 0,
            transform_detail_id = 0,
            # 合同号
            contract_number = params["contractNumber"],
            # 税控盘
            TCP = params["TCP"],
            # 是否续签
            renew = params["renew"],
            # 档案号
            document_id = document.id,
            
            leader_id = params["leaderId"],
            amount = params["amount"],
            unit = params["unit"],
            servicedetail_id = params["servicedetailId"],
            customer_id = params["customerId"],
            name = params["name"],
            remake = params["remake"],
            enddate = params["enddate"],
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            create_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            )

        enddate = params["enddate"][0:10]
        # 截止日期转换为日期型
        new_time = datetime.datetime.strptime(enddate, '%Y-%m-%d')
        months = 0
        if params["unit"] == "年":
            months = params["amount"] * 12
        elif params["unit"] == "月":
            months = params["amount"] * 1
        # 因为开闭取不到最后截止日期,所以这边截止日期加1个月
        new_time = new_time + relativedelta(months = 1)
        # 倒推开始日期
        month_ago = new_time - relativedelta(months = months)
        # 截止日期开始日期转换为str类型
        new_timestr = new_time.strftime('%Y%m%d')
        month_agostr = month_ago.strftime('%Y%m%d')
        # 使用pandas库列出开始日期到截止日期中的月份
        year_month_list = pd.date_range(start = month_agostr, end = new_timestr, freq = 'M').tolist()   
        data_year_months = year_month_list 
        # 需要的时间列表
#         data_year_months_conditions = []
        # 未完成
        status = KEEPINGING_AGENT_STATUS_FAIL
#         for data_year_month in data_year_months: 
#             data_year_month = data_year_month.strftime("%Y-%m")
#             if data_year_month[5:7] in ['01', '04', '07', '10']:
#                 data_year_months_conditions.append(data_year_month)
#         # 抄税 小规模季度，国税 小规模季度
#         itemconditions = COPY_TAX_NATIONAL_TAX_SMALL_SCALE_QUARTER
        result = []
        for month in data_year_months:
            # 现在日期
            now_timestr = datetime.datetime.now()           
            # to_pydatetime()方法，把list中的月份和现在日期比较
            if month.to_pydatetime() >= now_timestr:
                # 本月之后的默认未完成
                status = KEEPINGING_AGENT_STATUS_FAIL
            elif month.to_pydatetime() < now_timestr:
                # 本月之前的默认已完成
                status = KEEPINGING_AGENT_STATUS_SUCCESS  
            # 只取年月
            month = month.strftime("%Y-%m")
            for item in params["members"]:
                data = {
                    "keepaccount_id": agentkeeping.id,
                    "charger_id": item["chargerId"],
                    "matter": item["name"],
                    "status":status,
                    "month":month,
                    "remake": '无',
                    "evidence": '[]',
                    "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    "create_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    }
#                 if month in data_year_months_conditions:
#                     data = data
#                 else:
#                     if item in itemconditions:
#                         data = {
#                             "keepaccount_id": agentkeeping.id,
#                             "charger_id": 0,
#                             "matter": item,
#                             "status":'',
#                             "month":month,
#                             "remake": '无',
#                             "evidence": '[]',
#                             "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
#                             "create_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
#                         }
                result.append(data)
        AgentKeepingDetails.insert_many(result).execute()

        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")    

    @db.atomic()                   
    def editCusKeepAccount(self, params):
        """
       修改客户信息
        """
        print(params)
        print(params["id"])
        # 更新负责人期限
        #keepaccount = AgentKeeping.get(AgentKeeping.id == params["id"])
#         keepaccount.renew = params["renew"]
        #keepaccount.save()
        customer = Customer.get(Customer.id == params["customer_id"])
        customer.compname = params["compname"]
        customer.contacter = params["contacter"]
        customer.phone = params["phone"]
        customer.taxtype = params["taxtype"]
        customer.save()
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")

    @db.atomic()                   
    def batchKeepAccountCharger(self, params):
        """
        批量分配新的负责人
        """
#         print(params)

        if params["matter"] == AGENTKEEPING:
            # 代理记账总负责人变更（财税顾问）
            where_condition = True
            if params["keepaccountIds"]:
                where_condition = where_condition & (AgentKeeping.id.in_(params["keepaccountIds"]))
            if params["oldchargerId"]:
                where_condition = where_condition & (AgentKeeping.leader_id == params["oldchargerId"])
            if params["status"]:
                where_condition = where_condition & (AgentKeeping.status==params["status"])
            rows = AgentKeeping.select().where(where_condition)
            for row in rows:
                row.leader_id = params["newchargerId"]
                row.save()
        else:
            # 代理记账明细事项负责人变更（会计）
            where_condition = True
            if params["keepaccountIds"]:
                where_condition = where_condition & (AgentKeepingDetails.keepaccount_id.in_(params["keepaccountIds"]))
            if params["matter"]:
                where_condition = where_condition & (AgentKeepingDetails.matter==params["matter"])
            if params["oldchargerId"]:
                where_condition = where_condition & (AgentKeepingDetails.charger_id == params["oldchargerId"])
            if params["status"]:
                where_condition = where_condition & (AgentKeepingDetails.status==params["status"])
            keepaccountdetailrows = AgentKeepingDetails.select().where(where_condition)
            print(keepaccountdetailrows)
            for keepaccountdetailrow in keepaccountdetailrows:
                keepaccountdetailrow.charger_id = params["newchargerId"]
                keepaccountdetailrow.save()
        return super().resultSet(200, "批量转移成功", [])
        raise Exception("批量转移失败")

    @db.atomic()
    def statusset(self, params):
        """
        账本状态设定
        """
        print(params)
        AgentKeeping.update(status=params["status"], remake=params["memo"]) \
            .where(AgentKeeping.id.in_(params["keepaccountIds"])).execute()

        return super().resultSet(200, "状态设定成功", [])
        raise Exception("状态设定失败")

    @db.atomic()
    def delete(self, params):
        """
        批量删除
        """
#         print(params)
        where_condition = True
        if params["keepaccountIds"]:
            where_condition = where_condition & (AgentKeepingDetails.keepaccount_id.in_(params["keepaccountIds"]))
        if params["matter"]:
            where_condition = where_condition & (AgentKeepingDetails.matter.in_(params["matter"]))
        if params["oldchargerId"]:
            where_condition = where_condition & (AgentKeepingDetails.charger_id == params["oldchargerId"])
        # 已完成的账不需要变更
        where_condition = where_condition & (AgentKeepingDetails.status != KEEPINGING_AGENT_STATUS_SUCCESS)
        keepaccountdetailrows = AgentKeepingDetails.select().where(where_condition)
        for keepaccountdetailrow in keepaccountdetailrows:
            keepaccountdetailrow.charger_id = params["newchargerId"]
            keepaccountdetailrow.save()
        return super().resultSet(200, "更新成功", [])
        raise Exception("添加失败")

    def getTaxtypeoptions(self):
        """
            查询税务类型
            {'label': "qwe",'value': "qwe"}
        """
        result = []
        rows = Customer.select(Customer.taxtype).distinct()
        for row in rows:
            if (row.taxtype == "") | (row.taxtype == None):
                row.taxtype = "空白"
            result.append({'label': row.taxtype, 'value': row.taxtype})

        return super().resultSet(200, "查询所有税务类型请求成功", result)

    def getTCPS(self):
        """
            查询税控盘类型
        """
        result = []
        rows = AgentKeeping.select(AgentKeeping.TCP).distinct()
        for row in rows:
            if (row.TCP == None) | (row.TCP == ""):
                row.TCP = "空白"
            result.append(row.TCP)

        return super().resultSet(200, "查询所有税控盘类型请求成功", result)

    def getSbgjjs(self):
        """
           查询社保公积金类型
        """
        result = []
        rows = AgentKeeping.select(AgentKeeping.sbgjj).distinct()
        for row in rows:
            print(row.sbgjj)
            if (row.sbgjj == None) | (row.sbgjj == ""):
                row.sbgjj = "空白"
            result.append(row.sbgjj)

        return super().resultSet(200, "查询所有社保公积金类型请求成功", result)

    def updateTypeBatch(self,updateTypeForm):
        """
           修改记账类型
           参数：args 修改参数
        """

        try:
            if updateTypeForm['typeSX'] == '税务类型':
                ids = []
                for row in AgentKeeping.select(AgentKeeping.customer_id).where(AgentKeeping.id.in_(updateTypeForm['keepaccountIds'])):
                    ids.append(row.customer_id)
                Customer.update({Customer.taxtype : updateTypeForm['typeSSX']}).where(Customer.id.in_(ids)).execute()
            elif updateTypeForm['typeSX'] == '税控盘':
                AgentKeeping.update({AgentKeeping.TCP : updateTypeForm['typeSSX']}).where(AgentKeeping.id.in_(updateTypeForm['keepaccountIds'])).execute()
            elif updateTypeForm['typeSX'] == '社保公积金':
                AgentKeeping.update({AgentKeeping.sbgjj : updateTypeForm['typeSSX']}).where(AgentKeeping.id.in_(updateTypeForm['keepaccountIds'])).execute()
        except:
            return super().resultSet(400, "修改记账类型请求出错", "")



        return super().resultSet(200, "修改记账类型请求成功","")
